package com.qdhh.enrollment.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qdhh.enrollment.common.BusinessException;
import com.qdhh.enrollment.mapper.StudentMapper;
import com.qdhh.enrollment.model.Student;
import com.qdhh.enrollment.model.StudentProfile;
import com.qdhh.enrollment.service.StudentProfileService;
import com.qdhh.enrollment.service.StudentService;
import com.qdhh.enrollment.service.dto.LoginResult;
import com.qdhh.enrollment.util.WeChatUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * 学生服务实现类
 * 处理学生相关的业务逻辑，包括登录、身份认证等
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    private final WeChatUtil weChatUtil;
    private final StudentProfileService studentProfileService;

    public StudentServiceImpl(WeChatUtil weChatUtil, StudentProfileService studentProfileService) {
        this.weChatUtil = weChatUtil;
        this.studentProfileService = studentProfileService;
    }

    @Override
    public LoginResult login(String code, String nickName, String avatarUrl, String unionId) {
        if (!StringUtils.hasText(code)) {
            throw new BusinessException("登录凭证不能为空");
        }

        // 通过微信 code 获取 openid/unionid
        WeChatUtil.WeChatSessionInfo sessionInfo = weChatUtil.getSession(code);
        String openId = sessionInfo.getOpenId();
        String resolvedUnionId = StringUtils.hasText(unionId) ? unionId : sessionInfo.getUnionId();

        LocalDateTime now = LocalDateTime.now();
        Student student = getById(openId);

        if (student == null) {
            // 创建新学生记录
            student = Student.builder()
                .id(openId)
                .nick(StringUtils.hasText(nickName) ? nickName : null)
                .avatar(StringUtils.hasText(avatarUrl) ? avatarUrl : null)
                .unionId(StringUtils.hasText(resolvedUnionId) ? resolvedUnionId : null)
                .status(1) // 正常状态
                .identityVerified(0) // 默认未认证
                .deleted(0)
                .version(1)
                .createdAt(now)
                .updatedAt(now)
                .build();
            save(student);
        } else {
            if (StringUtils.hasText(nickName) && !nickName.equals(student.getNick())) {
                student.setNick(nickName);
            }
            if (StringUtils.hasText(avatarUrl) && !avatarUrl.equals(student.getAvatar())) {
                student.setAvatar(avatarUrl);
            }
            if (StringUtils.hasText(resolvedUnionId) && !resolvedUnionId.equals(student.getUnionId())) {
                student.setUnionId(resolvedUnionId);
            }
            student.setUpdatedAt(now);
            updateById(student);
        }

        // 使用 Sa-Token 进行登录
        StpUtil.login(openId);

        // 将 Student 信息存储到 Sa-Token Session
        StpUtil.getSession().set("student", student);
        StpUtil.getSession().set("identityVerified", student.getIdentityVerified());

        // 获取 Token
        String token = StpUtil.getTokenValue();

        return new LoginResult(student, token);
    }

    @Override
    public void updatePhone(String studentId, String phone) {
        if (!StringUtils.hasText(studentId)) {
            throw new BusinessException("用户未登录");
        }
        if (!StringUtils.hasText(phone) || !phone.matches("^\\d{11}$")) {
            throw new BusinessException("手机号格式不正确");
        }
        
        Student student = getById(studentId);
        if (student == null) {
            throw new BusinessException("用户不存在");
        }
        
        student.setPhone(phone);
        student.setUpdatedAt(LocalDateTime.now());
        updateById(student);
        
        // 更新 Session 中的学生信息
        if (StpUtil.isLogin()) {
            StpUtil.getSession().set("student", student);
        }
    }

    @Override
    public void updateStudentNo(String studentId, String studentNo) {
        if (!StringUtils.hasText(studentId)) {
            throw new BusinessException("用户未登录");
        }
        if (!StringUtils.hasText(studentNo)) {
            throw new BusinessException("学号不能为空");
        }
        
        Student student = getById(studentId);
        if (student == null) {
            throw new BusinessException("用户不存在");
        }
        
        student.setStudentNo(studentNo);
        student.setUpdatedAt(LocalDateTime.now());
        updateById(student);
        
        // 更新 Session 中的学生信息
        if (StpUtil.isLogin()) {
            StpUtil.getSession().set("student", student);
        }
        
        // 触发身份认证
        verifyIdentity(studentId, studentNo);
    }

    @Override
    public void verifyIdentity(String studentId, String studentNo) {
        if (!StringUtils.hasText(studentId) || !StringUtils.hasText(studentNo)) {
            return;
        }
        
        // 查询 student_profiles 表，检查学号是否存在
        StudentProfile profile = studentProfileService.getByStudentNo(studentNo);
        
        Student student = getById(studentId);
        if (student == null) {
            throw new BusinessException("用户不存在");
        }
        
        LocalDateTime now = LocalDateTime.now();
        
        if (profile != null) {
            // 学号存在，认证通过
            student.setIdentityVerified(1);
            student.setIdentityVerifiedAt(now);
            student.setIdentityVerifyMethod("auto");
            student.setIdentityVerifyRemark("通过学号匹配自动认证");
        } else {
            // 学号不存在，保持未认证状态
            student.setIdentityVerified(0);
            student.setIdentityVerifiedAt(null);
            student.setIdentityVerifyMethod(null);
            student.setIdentityVerifyRemark(null);
        }
        
        student.setUpdatedAt(now);
        updateById(student);
        
        // 更新 Sa-Token Session 中的认证状态
        if (StpUtil.isLogin()) {
            StpUtil.getSession().set("student", student);
            StpUtil.getSession().set("identityVerified", student.getIdentityVerified());
        }
    }

    @Override
    public Student getCurrentStudent() {
        if (!StpUtil.isLogin()) {
            throw new BusinessException("用户未登录");
        }
        
        String studentId = StpUtil.getLoginIdAsString();
        Student student = getById(studentId);
        
        if (student == null) {
            throw new BusinessException("用户不存在");
        }
        
        return student;
    }
}

